//
//  ConMyClubEditViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/7/3.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConMyClubEditViewController.h"
#import "ClubEditHeaderViewCell.h"
#import "ClubEditBtnCell.h"
#import "TakePhotoTool.h"
#import "ClubNetwork.h"
#import "MBProgressHUD+MJ.h"
#import "SZLAccountHelper.h"
#import "ConAddImageTextController.h"
#import "ConAddImageTextController.h"

@interface ConMyClubEditViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,assign) BOOL isModify;//记录是否是修改

@end

@implementation ConMyClubEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑俱乐部";
    
    [self setNavi];
    if (!self.editModel) {
        self.editModel = [[ClubModel alloc]init];
    }else {
        self.isModify = YES;
    }
    [self setUpView];
}
- (void)setNavi
{
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:RGBColor(255, 121, 201) forState:UIControlStateNormal];
    saveBtn.titleLabel.font = Font(16);
    [saveBtn addTarget:self action:@selector(uploadClubInfo) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
}
- (void)setUpView
{
    [self.view addSubview:self.tableView];
    UIButton *addBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenW-10-50, ScreenH-64-20-50, 50, 50)];
    [addBtn setTitle:@"＋" forState:UIControlStateNormal];
    addBtn.backgroundColor = [UIColor blueColor];
    [addBtn addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
}
- (void)addClick
{
    ConAddImageTextController *addVc = [[ConAddImageTextController alloc]init];
    addVc.isAdd = YES;
    __WEAK
    addVc.completeBlock = ^(ImageTitleModel *model) {
        [weakSelf.editModel.details addObject:model];
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:addVc animated:YES];
}
#pragma mark - Table view data delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section ==0) {
        return 0.01;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 345;
    }
    ClubEditBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubEditBtnCell class])];
    ImageTitleModel *desModel = self.editModel.details[indexPath.section-1];
    CGFloat cellH = [cell calculateDetailCellHWithModel:desModel];
    return cellH;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1+self.editModel.details.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ClubEditHeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubEditHeaderViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.editModel = self.editModel;
        cell.uploadPhoto = ^(UIButton *btn) {
            CGFloat scale;
            if (btn.tag == 1) {
                scale = 1.0;
            }else {
                scale = 309/125;
            }
            [self takeLogoBgPhoto:btn scale:scale];
        };
        return cell;
    }
    ClubEditBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubEditBtnCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ImageTitleModel *desModel = self.editModel.details[indexPath.section-1];
    cell.model = desModel;
    __WEAK
    cell.editBlock = ^(ImageTitleModel *model) {
        ConAddImageTextController *addVc = [[ConAddImageTextController alloc]init];
        addVc.model = model;
        addVc.completeBlock = ^(ImageTitleModel *model) {
            [weakSelf.tableView reloadData];
        };
        [weakSelf.navigationController pushViewController:addVc animated:YES];
    };
    cell.deleteBlock = ^(ImageTitleModel *model) {
        [weakSelf.editModel.details removeObject:model];
        [weakSelf.tableView reloadData];
    };
    return cell;
}
//上传logo和背景图
- (void)takeLogoBgPhoto:(UIButton *)btn scale:(CGFloat)scale
{
    [[TakePhotoTool shareTool]beginSelectWithScale:scale image:^(UIImage *image, NSString *path) {
        [btn setBackgroundImage:image forState:UIControlStateNormal];
        if (btn.tag == 2) {
            self.editModel.backgroundImg = path;
        } else {
            self.editModel.clubLogo = path;
        }
    }];
}
#pragma mark -------上传信息------------------
- (void)uploadClubInfo
{
    if (!self.editModel.clubLogo) {
        [MBProgressHUD showError:@"请上传logo图片"];
        return;
    }
    if (!self.editModel.clubName) {
        [MBProgressHUD showError:@"请填写俱乐部名称"];
        return;
    }
    if (!self.editModel.clubName) {
        [MBProgressHUD showError:@"请填写俱乐部介绍"];
        return;
    }
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"clubName"] = self.editModel.clubName;
    parame[@"content"] = self.editModel.content;
    parame[@"clubLogo"] = self.editModel.clubLogo;
    parame[@"backgroundImg"] = self.editModel.backgroundImg;
    if (self.isModify) {
        parame[@"id"] = @(self.editModel.ID);
    }
    NSMutableArray *details = [NSMutableArray array];
    for (ImageTitleModel *model in self.editModel.details) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"clubImage"] = [model.clubImageList componentsJoinedByString:@"#"];
        if (!model.clubContent) {
            dict[@"clubContent"] = @"";
        }else {
            dict[@"clubContent"] = model.clubContent;
        }
        [details addObject:dict];
    }
    //NSJSONWritingPrettyPrinted设置这个可以提高阅读性 不设置传0
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:details options:0 error:nil];
    parame[@"clubDetailList"] = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self showClearBgWaiter];
    if (self.isModify) {
        [ClubNetwork modifyClubInfoWithParame:parame response:^(BOOL success, NSString *msg) {
            [self hideWaiter];
            if (success) {
                [MBProgressHUD showSuccess:@"修改成功"];
                if (self.refreshBlock) {
                    self.refreshBlock();
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else {
                [MBProgressHUD showError:msg];
            }
        }];
    }else {
        [ClubNetwork uploadClubInfoWithParame:parame response:^(BOOL success, NSString *msg) {
            [self hideWaiter];
            if (success) {
                [MBProgressHUD showSuccess:@"上传成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else {
                [MBProgressHUD showError:msg];
            }
        }];
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionFooterHeight = 0.01;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ClubEditHeaderViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ClubEditHeaderViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ClubEditBtnCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ClubEditBtnCell class])];
    }
    return _tableView;
}

@end
